package main

import (
	"context"
	"flag"
	"fmt"
	"math/rand"
	"net/http"
	"sync"
)

var ShareHost = ""
var SharePort = 9696
var SharePath = "./"

func StaticFileServer(host string, port int, sharePath string) {
	http.Handle("/", http.FileServer(http.Dir(sharePath)))
	var server http.Server
	var mux = &sync.Mutex{}
	var isStopped bool
	ctx, cancel := context.WithCancel(context.Background())
	go func() {
		defer mux.Unlock()
		fmt.Printf("Press Any key to Stop Server.\n")
		var s string
		_, _ = fmt.Scanln(&s)
		mux.Lock()
		isStopped = true
		_ = server.Shutdown(ctx)
		cancel()
	}()

	for {
		addr := fmt.Sprintf("%s:%d", host, port)
		fmt.Println(fmt.Sprintf("Http Server Start At %s\n", addr))
		server.Addr = addr
		err := server.ListenAndServe()
		fmt.Println(err)
		if err != nil {
			port = rand.Intn(9999)
		}
		mux.Lock()
		if isStopped {
			break
		}
		mux.Unlock()
	}
	return
}

func main() {
	flag.StringVar(&ShareHost, "host", "", "share host")
	flag.IntVar(&SharePort, "p", 9696, "share port")
	flag.StringVar(&SharePath, "d", "./", "share file path")
	flag.Parse()
	StaticFileServer(ShareHost, SharePort, SharePath)
}
